package cn.sycoder.controller;

import cn.sycoder.entity.Dept;
import cn.sycoder.entity.User;
import cn.sycoder.exception.BusinessException;
import cn.sycoder.mapper.DeptMapper;
import cn.sycoder.resp.Code;
import cn.sycoder.service.IDeptService;
import cn.sycoder.utils.JsonUtil;
import cn.sycoder.utils.JwtUtil;
import cn.sycoder.utils.UserUtils;
import cn.sycoder.vo.DeptVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;

import java.util.*;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author 杨润发
 * @since 2024-10-20
 */
@RestController
@RequestMapping("/api/Dept")
@Api(tags = "公司管理")
@Transactional(rollbackFor = Exception.class)
public class DeptController {

    @Autowired
    IDeptService service;

    @Autowired
    DeptMapper mapper;

    @PostMapping("/list")
    @ApiOperation(value = "公司管理-获取公司列表")
    public Map<String, Object> deptList(@RequestParam(defaultValue = "1") int page,
                                        @RequestParam(defaultValue = "10") int limit,
                                        @RequestParam(value = "deptName", required = false) String deptName,
                                        @RequestParam(value = "deptNo", required = false) String deptNo) {

        // 创建响应结果
        Map<String, Object> response = new HashMap<>();

        // 创建分页查询
        Page<Dept> objectPage = new Page<>(page, limit);

        // 构造sql
        QueryWrapper<Dept> wrapper = new QueryWrapper<>();
        Map<String, Object> params = new HashMap<>();
        params.put("dept_name", deptName);
        params.put("dept_no", deptNo);
        wrapper.allEq(params, false); // 如果条件中参数为空，则从条件中去除该参数

        try {
            // 执行分页查询
            Page<Dept> deptPage = mapper.selectPage(objectPage, wrapper);

            if (deptPage != null) {
                // 获取部门总数
                long count = deptPage.getTotal();
                response.put("count", count); // 响应查询总数
                response.put("data", deptPage); // 响应查询结果
                response.put("success", true); // 查询成功
            } else {
                response.put("success", false);
                response.put("msg", "服务器异常！");
            }
        }catch (BusinessException e){
            new BusinessException(Code.BUSINESS_ERR,"业务处理异常，请稍后再试！");
        }
        return response;
    }


    @PostMapping("/save")
    @ApiOperation(value = "公司管理-保存（添加编辑）")
    public Map<String, Object> deptSave(@RequestParam(value = "deptId", required = false) Long deptId,
                                        @RequestParam(value = "deptName") String deptName,
                                        @RequestParam(value = "deptNo") String deptNo,
                                        @RequestParam(value = "token") String token) {

        // 获取登录用户名（修改人）
        String username = JwtUtil.extractUsername(token);


        // 创建响应结果
        Map<String, Object> response = new HashMap<>();
        Dept dept = new Dept();
        dept.setDeptId(deptId);
        dept.setDeptName(deptName);
        dept.setDeptNo(deptNo);
        dept.setEditUser(username);
        dept.setEditTime(new Date());

        // 保存或更新操作
        boolean ret = false;
        try {
            if (dept.getDeptId() != null) {
                // 有id表示更新操作
                ret = service.updateById(dept);
            } else {
                // 无id表示保存操作
                ret = service.save(dept);
            }
        }catch (BusinessException e){
            new BusinessException(Code.BUSINESS_ERR,"业务处理异常，请稍后再试！");
        }

        if (ret) {
            response.put("success", true);
        } else {
            response.put("msg", "服务器异常！");
        }
        return response;
    }


    @GetMapping("/delete")
    @ApiOperation(value = "公司管理-删除公司")
    public Map<String, Object> deptDelete(@RequestParam String ids) {

        // 创建响应结果
        Map<String, Object> response = new HashMap<>();

        try {
            boolean ret = service.removeById(ids);
            if (ret) {
                response.put("success", true);
            } else {
                response.put("msg", "服务器异常！");
            }
        }catch (BusinessException e){
            new BusinessException(Code.BUSINESS_ERR,"业务处理异常，请稍后再试！");
        }
        return response;
    }
}
